package com.ant.backstage.controller;

import com.alibaba.fastjson.JSONObject;
import com.ant.backstage.facade.ApiReturn;
import com.ant.backstage.facade.code.ApiReturnCode;
import com.ant.backstage.facade.dto.UserDTO;
import com.ant.backstage.facade.enums.UploadFileEnum;
import com.ant.backstage.facade.model.FileInfo;
import com.ant.backstage.facade.model.User;
import com.ant.backstage.facade.request.*;
import com.ant.backstage.facade.response.PageFrontResponse;
import com.ant.backstage.service.FileInfoService;
import com.ant.backstage.service.FileUploadService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

@Api(tags = "文件处理API")
@RestController
@RequestMapping("/api/v1/file")
public class FileUploadController {

    private static Logger logger = LogManager.getLogger(FileUploadController.class);

    @Autowired
    FileUploadService fileUploadService;
    @Resource
    FileInfoService fileInfoService;

    @Resource
    CommonMethod commonMethod;
    @Resource
    MapperFacade mapperFacade;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ApiOperation(value = "文件上传", response = ApiReturn.class)
    public String upload(MultipartFile file) throws Exception {
        fileUploadService.upload(file, null);

        return null;
    }

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    @ApiOperation(value = "文件下载[暂留]", response = ApiReturn.class)
    public String downloadFile(HttpServletResponse response) throws IOException {
        fileUploadService.download(response, "上传模板");
        return null;
    }

    @RequestMapping(value = "/uploadAvatarImg", method = RequestMethod.POST)
    @ApiOperation(value = "头像上传[本地]", response = ApiReturn.class)
    public ApiReturn uploadAvatarImg(MultipartFile[] file, HttpServletRequest request) {
        //1. 获取当前登录的用户
        ApiReturn apiReturn = new ApiReturn();
        UserDTO userInfoByToken = commonMethod.getUserInfoByToken(request);
        if (!Optional.ofNullable(userInfoByToken).isPresent()) {
            apiReturn.setCode(ApiReturnCode.NOT_AUTHORIZED.getCode());
            apiReturn.setMsg(ApiReturnCode.NOT_AUTHORIZED.getMessage());
            return apiReturn;
        }
        apiReturn = fileUploadService.uploadAvatarImg(file, userInfoByToken);
        return apiReturn;
    }

    /**
     * @return
     * @Author zhangyu      https://blog.csdn.net/cl939974883/article/details/119304334
     * @Description
     * @Date 10:44 2022/1/19
     * @Param springboot  实现gitee图床功能
     **/
    @RequestMapping(value = "/gitee/upload", method = RequestMethod.POST)
    @ApiOperation(value = "上传文件[GITEE]", response = ApiReturn.class)
    public ApiReturn giteeUploadFile(@RequestParam("file") MultipartFile file, @RequestParam String fileType) throws IOException {
        /*Content type 'multipart/form-data;boundary=----WebKitFormBoundaryoMJ4jRLg3zbSxBt6;charset=UTF-8' not supported
            上传在上传文件的时候，spring框架会自动装配文件类型, 使用@RequestBody接收对象，所对应的content-type :application/json。所以当使用@RequestBody和文件上传的时候，会报错。
        */
        logger.info("uploadFile()请求已来临...");
        ApiReturn apiReturn = fileUploadService.giteeUploadFile( file,fileType);
        return apiReturn;
    }

    @RequestMapping(value = "/saveFileInfo", method = RequestMethod.POST)
    @ApiOperation(value = "保存上传文件模板", response = ApiReturn.class)
    public ApiReturn saveFileInfo(@RequestBody UploadFileRequest uploadFileRequest, HttpServletRequest request) {
        logger.info("保存上传文件模板 入参 uploadFileRequest={}",JSONObject.toJSONString(uploadFileRequest));
        UserDTO userInfoByToken = commonMethod.getUserInfoByToken(request);
        ApiReturn apiReturn = fileUploadService.saveFileInfo(uploadFileRequest,userInfoByToken);
        return apiReturn;
    }

    @RequestMapping(value = "/gitee/uploadAvatarImg", method = RequestMethod.POST)
    @ApiOperation(value = "上传用户头像[GITEE]", response = ApiReturn.class)
    public ApiReturn giteeUploadAvatarImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        logger.info("上传用户头像...");
        UserDTO userInfoByToken = commonMethod.getUserInfoByToken(request);
        ApiReturn apiReturn = fileUploadService.giteeUploadAvatarImg(file, UploadFileEnum.UPLOAD_FILE_IMG.getCode(), userInfoByToken.getUid());
        return apiReturn;
    }

    @RequestMapping(value = "/gitee/del", method = RequestMethod.POST)
    @ApiOperation(value = "删除已上传文件[GITEE]", response = ApiReturn.class)
    public ApiReturn delFile(@RequestBody DelGiteeImgRequest request) {
        logger.info("删除已文件 入参DelGiteeImgRequest={}", com.alibaba.fastjson.JSONObject.toJSONString(request));
        ApiReturn apiReturn = fileUploadService.delGiteeFile(request);
        return apiReturn;
    }

    @ApiOperation(value = "文件管理分页", response = PageFrontResponse.class)
    @RequestMapping(value = "/selectFilePage", method = RequestMethod.POST)
    public PageFrontResponse selectFilePage(@RequestBody FilePageInfoRequest filePageInfoRequest) {
        logger.info("文件管理分页 入参 filePageInfoRequest={}", JSONObject.toJSONString(filePageInfoRequest));
        FileInfo fileInfo = mapperFacade.map(filePageInfoRequest, FileInfo.class);
        PageInfo objectPageInfo = fileInfoService.selectFilePage(fileInfo, filePageInfoRequest.getPageNum(), filePageInfoRequest.getPageSize());
        logger.info("文件管理分页 objectPageInfo={}", JSONObject.toJSONString(objectPageInfo));

        PageFrontResponse pageFrontResponse = new PageFrontResponse();
        if (objectPageInfo == null) {
            pageFrontResponse.setResultMsg(ApiReturnCode.NO_TERM_DATAS.getMessage());
            pageFrontResponse.setResultCode(ApiReturnCode.NO_TERM_DATAS.getCode());
            return pageFrontResponse;
        }
        logger.info("查分页用户信息 出参 objectPageInfo={}", JSONObject.toJSONString(objectPageInfo));
        pageFrontResponse.setData(objectPageInfo.getList()).setPageNum(objectPageInfo.getPageNum())
                .setPages(objectPageInfo.getPages()).setPageSize(objectPageInfo.getPageSize())
                .setTotal(objectPageInfo.getTotal());
        pageFrontResponse.setResultMsg(ApiReturnCode.SUCCESSFUL.getMessage());
        pageFrontResponse.setResultCode(ApiReturnCode.SUCCESSFUL.getCode());
        return pageFrontResponse;
    }

    @RequestMapping(value = "/updateFileStatus", method = RequestMethod.GET)
    @ApiOperation(value = "修改文件状态", response = ApiReturn.class)
    public ApiReturn updateFileStatus(UpdateFileStatusRequest updateFileStatusRequest) {
        logger.info("修改文件状态 入参 updateFileStatusRequest={}", JSONObject.toJSONString(updateFileStatusRequest));
        ApiReturn apiReturn = fileInfoService.updateFileStatus(updateFileStatusRequest);
        return apiReturn;
    }

    @RequestMapping(value = "/exportData", method = RequestMethod.GET)
    @ApiOperation(value = "导出数据[模板]", response = ApiReturn.class)
    public ApiReturn exportData(ExportDataRequest exportDataRequest, HttpServletRequest request) throws Exception {
        logger.info("导出数据[模板] 入参 exportDataRequest={}", JSONObject.toJSONString(exportDataRequest));
        UserDTO userInfoByToken = commonMethod.getUserInfoByToken(request);
        ApiReturn apiReturn = fileInfoService.exportData(exportDataRequest,userInfoByToken);
        return apiReturn;
    }

}
